//
//  USMediaUploadManager.m
//  us
//
//  Created by lhx on 2025/5/15.
//

#import "USMediaUploadManager.h"

#import <QCloudCOSXML/QCloudCOSXMLTransfer.h>
@interface USMediaUploadManager ()

@property (nonatomic,strong)NSString * albumFirstDirectory;
@property (nonatomic,strong)NSString * albumSecondDirectory;
@end

@implementation USMediaUploadManager

 
+ (void)uploadImages:(NSArray<USMediaResult *> *)mediaList
 albumFirstDirectory:(NSString *)albumFirstDirectory
albumSecondDirectory:(NSString *)albumSecondDirectory
            progress:(void (^)(NSInteger current, NSInteger total))progressHandler
             success:(void (^)(NSArray<USPhotoModel *> *models))success
             failure:(void (^)(NSError *error))failure {
    
    NSMutableArray<USPhotoModel *> *results = [NSMutableArray arrayWithCapacity:mediaList.count];
    for (NSInteger i = 0; i < mediaList.count; i++) {
        [results addObject:[USPhotoModel new]];
    }
    
    dispatch_group_t group = dispatch_group_create();
    __block BOOL hasError = NO;
    __block NSError *firstError = nil;
    
    NSInteger totalCount = mediaList.count;
     __block NSInteger completedCount = 0;
    
    USMediaUploadManager *manager = [[USMediaUploadManager alloc]init];
    manager.albumFirstDirectory = albumFirstDirectory;
    manager.albumSecondDirectory = albumSecondDirectory;
    for (NSInteger i = 0; i < mediaList.count; i++) {
        USMediaResult *media = mediaList[i];
        
        NSString *uuid = NSUUID.UUID.UUIDString;

        NSString *fileName = @"";
        if (media.type == USMediaTypeImage) {
            fileName = [uuid stringByAppendingPathExtension:@"jpg"];
        }else if (media.type == USMediaTypeVideo){
            fileName = [uuid stringByAppendingPathExtension:@"mp4"];
        }else if (media.type == USMediaTypeLivePhoto){
            //live图先上传图片
            fileName = [uuid stringByAppendingPathExtension:@"jpg"];
        }
   
        dispatch_group_enter(group);
        
        void (^incrementProgress)(void) = ^{
            @synchronized (results) {
                completedCount++;
                if (progressHandler && totalCount != 1) {
                    progressHandler(completedCount, totalCount);
                }
            }
        };
             
        USPhotoModel *model = [[USPhotoModel alloc] init];
//        model.albumId = manager.album.albumId;
        model.photoFirstDirectory = manager.albumFirstDirectory;
        if (media.type == USMediaTypeVideo) {
            model.photoSecondDirectory = manager.albumSecondDirectory;
        }
        model.fileName = fileName;
        model.type = media.type;
        model.recordDate = media.customDate;
        
        [manager uploadUSMedia:media fileName:fileName progress:^(CGFloat progress,NSInteger size) {
            if (totalCount == 1 && progressHandler) {
                progressHandler(progress * 100, 1);
            }
            model.size = size;
        } success:^(NSString *cosUrl) {
            model.cosUrl = cosUrl;

            if (media.type == USMediaTypeLivePhoto) {
                NSString *movFileName = [uuid stringByAppendingPathExtension:@"mp4"];
                [manager uploadUSMedia:media isLiveMov:YES fileName:movFileName progress:^(CGFloat progress,NSInteger size) {
                    model.liveMovSize = size;
                } success:^(NSString *cosUrl) {
                    model.liveMovUrl = cosUrl;
                    model.liveMoveFileName = movFileName;
                    @synchronized (results) {
                        results[i] = model;
//                        [results addObject:model];
                    }
                    incrementProgress();
                    dispatch_group_leave(group);
                } failure:^(NSError *error) {
                    @synchronized (results) {
                        hasError = YES;
                        if (!firstError) {
                            firstError = error;
                        }
                    }
                    incrementProgress();
                    dispatch_group_leave(group);
                }];
            }else{
                @synchronized (results) {
                    results[i] = model;
//                    [results addObject:model];
                }
                incrementProgress();
                dispatch_group_leave(group);
            }
        
        } failure:^(NSError *error) {
            @synchronized (results) {
                hasError = YES;
                if (!firstError) {
                    firstError = error;
                }
            }
            incrementProgress();
            dispatch_group_leave(group);
        }];
    }
    
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        if (hasError) {
            if (failure) failure(firstError);
        } else {
            if (success) success([results copy]);
        }
    });
}

- (void)uploadUSMedia:(USMediaResult *)media
                fileName:(NSString *)fileName
                progress:(void (^)(CGFloat progress, NSInteger size))progress
                 success:(void (^)(NSString *cosUrl))success
              failure:(void (^)(NSError *error))failure {
    [self uploadUSMedia:media
              isLiveMov:NO
               fileName:fileName
               progress:progress
                success:success
                failure:failure];
}
- (void)uploadUSMedia:(USMediaResult *)media
            isLiveMov:(BOOL)isLiveMov
            fileName:(NSString *)fileName
             progress:(void (^)(CGFloat progress, NSInteger size))progress
              success:(void (^)(NSString *cosUrl))success
              failure:(void (^)(NSError *error))failure {
    
    QCloudCOSXMLUploadObjectRequest *put = [QCloudCOSXMLUploadObjectRequest new];
    put.bucket = @"us-1258555951";
    
    if (media.type == USMediaTypeImage) {
        UIImage *image = [UIImage imageWithContentsOfFile:media.filePath];
        NSData *imageData = UIImageJPEGRepresentation(image, 0.8);

        put.body = imageData;
        put.contentType = @"image/jpeg";
        put.object = [NSString stringWithFormat:@"%@/%@",self.albumFirstDirectory,fileName];

    }else if (media.type == USMediaTypeVideo) {
        put.body = [NSURL fileURLWithPath:media.filePath];
        put.contentType = @"video/mp4";
        NSString *pbjetc = [NSString stringWithFormat:@"%@/%@/%@",self.albumFirstDirectory,self.albumSecondDirectory,fileName];
        put.object = pbjetc;
    }else if (media.type == USMediaTypeLivePhoto){
        if (isLiveMov) {
            put.body = [NSURL fileURLWithPath:media.liveMov];
//            put.contentType = @"video/quicktime";
            put.contentType = @"video/mp4";
            put.object = [NSString stringWithFormat:@"%@/%@/%@",self.albumFirstDirectory,self.albumSecondDirectory,fileName];
        }else{
            UIImage *image = [UIImage imageWithContentsOfFile:media.filePath];
            NSData *imageData = UIImageJPEGRepresentation(image, 0.8);

            put.body = imageData;
            put.contentType = @"image/jpeg";
            put.object = [NSString stringWithFormat:@"%@/%@",self.albumFirstDirectory,fileName];

        }
    }

    // ✅ 添加进度回调
    [put setSendProcessBlock:^(int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend) {
        if (totalBytesExpectedToSend > 0 && progress) {
            CGFloat percent = (CGFloat)totalBytesSent / (CGFloat)totalBytesExpectedToSend;
            NSLog(@"bytesSent = %lli, totalBytesSent = %lli, totalBytesExpectedToSend = %lli ",bytesSent,totalBytesSent,totalBytesExpectedToSend);
            dispatch_async(dispatch_get_main_queue(), ^{
                progress(percent,totalBytesExpectedToSend);
            });
        }
    }];

    // ✅ 上传完成回调
    put.finishBlock = ^(QCloudUploadObjectResult *result, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (error) {
                if (failure) failure(error);
            } else {
                if (success) success(result.location);
            }
        });
    };
    
    [[QCloudCOSTransferMangerService defaultCOSTransferManager] UploadObject:put];
}



+ (void)uploadImageToCOS:(UIImage *)image
                progress:(void (^)(CGFloat progress))progress
                 success:(void (^)(NSString *cosUrl))success
                 failure:(void (^)(NSError *error))failure {
    
    NSData *imageData = UIImageJPEGRepresentation(image, 0.8);
    NSString *fileName = [NSString stringWithFormat:@"%@.jpg", NSUUID.UUID.UUIDString];
    NSString *objectKey = [NSString stringWithFormat:@"album-%@", fileName];

    QCloudCOSXMLUploadObjectRequest *put = [QCloudCOSXMLUploadObjectRequest new];
    put.bucket = @"us-1258555951";
    put.object = objectKey;
    put.body = imageData;
    put.contentType = @"image/jpeg";

    // ✅ 添加进度回调
    [put setSendProcessBlock:^(int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend) {
        if (totalBytesExpectedToSend > 0 && progress) {
            CGFloat percent = (CGFloat)totalBytesSent / (CGFloat)totalBytesExpectedToSend;
            dispatch_async(dispatch_get_main_queue(), ^{
                progress(percent);
            });
        }
    }];

    // ✅ 上传完成回调
    put.finishBlock = ^(QCloudUploadObjectResult *result, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (error) {
                if (failure) failure(error);
            } else {
                if (success) success(result.location);
            }
        });
    };
    
    [[QCloudCOSTransferMangerService defaultCOSTransferManager] UploadObject:put];
}
@end
